<template>
  <div class="app-container">
    <div class="view-title">角色管理</div>

    <!-- <el-form :model="queryParams" ref="queryForm" size="small" :inline="true">
      <el-form-item label="角色名称" prop="roleName">
        <el-input
          v-model="queryParams.roleName"
          placeholder="请输入角色名称"
          clearable
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
      </el-form-item>
    </el-form> -->
    <el-row :gutter="10">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-permission="['role:add']"
          >新增</el-button
        >
      </el-col>
    </el-row>
    <el-table
      :data="tableData"
      v-loading="loading"
      element-loading-text="正在加载中"
      :header-cell-style="{
        borderColor: '#F0F0F0',
        height: '51px',
        background: '#F0F0F0',
        color: '#333',
      }"
      :row-style="{ height: '51px' }"
      :cell-style="{ borderColor: '#F0F0F0' }"
      style="width: 100%; margin-top: 20px"
    >
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="name" label="角色名称" />

      <el-table-column prop="updated_at" label="更新时间" />
      <el-table-column prop="created_at" label="创建时间" />
      <el-table-column prop="prop" label="操作" width="200">
        <template slot-scope="{ row }">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(row)"
            v-permission="['role:edit']"
            >修改</el-button
          >

          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(row)"
            v-permission="['role:delete']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <el-dialog
      :title="title"
      :visible.sync="open"
      width="500px"
      append-to-body
      :before-close="cancel"
    >
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="角色名称">
              <el-input
                v-model="form.name"
                placeholder="请输入角色名称"
              ></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="路由权限">
              <div class="role-container">
                <el-tree
                  :default-expand-all="expand"
                  :key="treeKey"
                  :default-checked-keys="power_grouop_ids"
                  ref="tree"
                  :data="treeData"
                  node-key="id"
                  :check-strictly="true"
                  :props="{ label: 'name' }"
                  show-checkbox
                >
                </el-tree>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer">
        <el-button type="" @click="showOrClose">{{
          `${expand === true ? "收起" : "展开"}权限`
        }}</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getMenuList,
  getRoleList,
  getRole,
  addRole,
  updateRole,
  deleteRole,
  getAllPower,
} from "@/api/role";
export default {
  data() {
    return {
      expand: true,
      treeKey: 1,
      loading: false,
      dialogType: "edit",
      queryParams: {
        roleName: "",
      },
      treeData: [],
      power_grouop_ids: [],
      form: { name: "" },
      // 表单校验
      rules: {
        menuName: [
          { required: true, message: "菜单名称不能为空", trigger: "blur" },
        ],
        orderNum: [
          { required: true, message: "菜单顺序不能为空", trigger: "blur" },
        ],
        path: [
          { required: true, message: "路由地址不能为空", trigger: "blur" },
        ],
      },
      title: "",
      open: false,
      tableData: [],
    };
  },
  created() {
    this.getList();
    this.loadData();
  },
  methods: {
    showOrClose() {
      this.expand = !this.expand;
      ++this.treeKey;
    },
    /** 查询权限列表 */
    getList() {
      this.loading = true;
      getAllPower().then((response) => {
        this.loading = false;
        this.treeData = response.data;
      });
    },
    /** 查询角色列表 */
    loadData() {
      let params = getRoleList().then((response) => {
        this.tableData = response.data;
      });
    },
    handleQuery() {
      this.loadData();
    },
    submitForm() {
      let res = this.$refs.tree.getCheckedKeys().join();

      this.$refs["formRef"].validate((valid) => {
        if (valid) {
          let params = {
            ...this.form,
            power_grouop_ids: res,
          };
          if (this.dialogType === "edit") {
            updateRole(params).then((response) => {
              this.$message.success("修改成功");
              this.open = false;
              this.loadData();
            });
          } else {
            addRole(params).then((response) => {
              this.$message.success("新增成功");
              this.open = false;
              this.loadData();
            });
          }
        }
      });
    },
    cancel() {
      this.open = false;
      this.reset();
    },

    handleAdd() {
      this.dialogType = "add";
      this.open = true;
      this.title = "修改菜单";
    },
    handleUpdate(row) {
      this.dialogType = "edit";
      this.form = this.$options.data().form;
      getRole(row.id).then((response) => {
        this.form.id = response.data.id;
        this.form.name = response.data.name;
        this.power_grouop_ids = response.data.power_grouop_ids.split(",");
        this.open = true;
        this.title = "修改菜单";
      });
    },
    handleDelete(row) {
      this.$confirm("是否确认删除？")
        .then(() => {
          deleteRole({ ids: row.id }).then((res) => {
            this.loadData();
            this.$message.success("删除成功");
          });
        })
        .catch(() => {});
    },
    // 表单重置
    reset() {
      this.power_grouop_ids = [];
      this.form = this.$options.data().form;
      ++this.treeKey;
      this.$refs["formRef"].clearValidate();
    },
  },
};
</script>

<style lang="scss" scoped>
.role-container {
  height: 500px;
  overflow-y: auto;
  &::-webkit-scrollbar-track-piece {
    background: #d3dce6;
  }

  &::-webkit-scrollbar {
    width: 6px;
  }

  &::-webkit-scrollbar-thumb {
    background: #99a9bf;
    border-radius: 20px;
  }
}
</style>
